using _RobotInspection.Models;
using Serilog;
using System.Net;
using System.Text.Json;

namespace _RobotInspection.Middlewares
{
    ///
    /// 全局异常处理中间件
    /// 

    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            context.Response.ContentType = "application/json";
            
            var response = new {
                StatusCode = 0,
                Message = "",
                DetailedMessage = "",
                StackTrace = ""
            };

            switch (exception)
            {
                case BadHttpRequestException:
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    response = new
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = "请求参数错误",
                        DetailedMessage = exception.Message,
                        StackTrace = exception.StackTrace
                    };
                    break;
                case UnauthorizedAccessException:
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    response = new
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = "未授权访问",
                        DetailedMessage = exception.Message,
                        StackTrace = exception.StackTrace
                    };
                    break;
                case NotImplementedException:
                    context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                    response = new
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = "功能未实现",
                        DetailedMessage = exception.Message,
                        StackTrace = exception.StackTrace
                    };
                    break;
                case BusinessException businessException:
                    context.Response.StatusCode = (int)HttpStatusCode.OK; // 业务异常通常返回200，通过错误码标识
                    response = new
                    {
                        StatusCode = businessException.Code,
                        Message = businessException.Message,
                        DetailedMessage = "",
                        StackTrace = ""
                    };
                    break;
                default:
                    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    response = new
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = "发生内部错误",
                        DetailedMessage = exception.Message,
                        StackTrace = exception.StackTrace
                    };
                    break;
            }

            // 记录错误日志
            Log.Error(exception, "发生未处理的异常: {Message}", exception.Message);

            await context.Response.WriteAsync(JsonSerializer.Serialize(response));
        }
    }
}